<template>
  <div class="consult-calendar">
    <!-- 头部 -->
    <div class="header">
      <h2>您好，{{ userStore.name }}！</h2>
      <p>这是您的预约日历，请点击日期查看详细预约信息</p>
    </div>

    <!-- 数据概览 -->
    <div class="stats-cards">
      <el-card shadow="hover" class="card">
        <div class="card-title">今日预约</div>
        <div class="card-value">{{ todayAppointments }}</div>
      </el-card>
      <el-card shadow="hover" class="card">
        <div class="card-title">待确认预约</div>
        <div class="card-value warning">{{ pendingAppointments }}</div>
      </el-card>
      <el-card shadow="hover" class="card">
        <div class="card-title">预约总计</div>
        <div class="card-value success">{{ totalAppointments }}</div>
      </el-card>
    </div>

    <!-- 日历组件 -->
    <el-card shadow="never" class="calendar-card">
      <el-calendar v-model="currentDate">
        <!-- 自定义单元格内容 -->
        <template #date-cell="{ data }">
          <div class="cell-content" @click="handleDateClick(data.day)">
            <div class="day">{{ data.day.split('-')[2] }}</div>
            <div v-if="getAppointmentsByDate(data.day).length" class="appointment-mark">
              <el-badge :value="getAppointmentsByDate(data.day).length" type="warning"/>
            </div>
          </div>
        </template>
      </el-calendar>
    </el-card>

    <!-- 日期详情弹窗 -->
    <el-dialog v-model="dialogVisible" :title="selectedDate + ' 的预约'" width="40%">
      <div class="appointment-content">
        <el-empty
            v-if="selectedAppointments.length === 0"
            description="当日暂无预约"
        />
        <el-timeline>
          <el-timeline-item
              v-for="appointment in selectedAppointments"
              :key="appointment.id"
              :timestamp="appointment.time"
              placement="top"
          >
            <el-card>
              <h4>用户：{{ appointment.userName }}</h4>
              <div class="info-row">
                <span class="label">类型：</span>
                <dict-tag :options="consultation_type" :value="appointment.method" class="value"/>
                <span class="label">状态：</span>
                <dict-tag :options="appointment_status" :value="appointment.status" class="value"/>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, getCurrentInstance, ref} from 'vue'
import useUserStore from "../../store/modules/user.js";
import {initAppointmentList} from "@/api/appointment/appointment.js";
import {parseTime} from "@/utils/ruoyi.js";
import DictTag from "@/components/DictTag/index.vue";

const userStore = useUserStore()
const {proxy} = getCurrentInstance();
const {consultation_type, appointment_status} = proxy.useDict("consultation_type", "appointment_status")

// 模拟预约数据
const appointments = ref([])

// 当前选中日期 & 弹窗控制
const currentDate = ref(new Date())
const selectedDate = ref('')
const dialogVisible = ref(false)
const selectedAppointments = ref([])

// 按日期分组预约数据
const appointmentsMap = computed(() => {
  const map = {}
  appointments.value.forEach(apt => {
    const dateKey = apt.time.split(' ')[0] // 提取 YYYY-MM-DD
    if (!map[dateKey]) map[dateKey] = []
    map[dateKey].push(apt)
  })
  return map
})

// 获取某天的预约
const getAppointmentsByDate = (date) => {
  return appointmentsMap.value[date] || []
}

// 点击日期单元格
const handleDateClick = (date) => {
  selectedDate.value = date
  selectedAppointments.value = getAppointmentsByDate(date)
  dialogVisible.value = true
}

// 状态颜色映射
const statusColor = (status) => {
  const map = {'待确认': 'warning', '已确认': 'success', '取消': 'info'}
  return map[status] || ''
}

// 统计计算
const todayAppointments = computed(() => {
  const today = formatDate(currentDate.value)
  return getAppointmentsByDate(today).length
})

const pendingAppointments = computed(() => {
  return appointments.value.filter(a => a.status === '待确认').length
})

const totalAppointments = computed(() => appointments.value.length)

// 工具函数 - 格式化日期为 YYYY-MM-DD
const formatDate = (date) => {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

const getAppointmentList = () => {
  initAppointmentList(userStore.id).then(res => {
    // 转换后端数据结构
    appointments.value = res.rows.map(item => ({
      id: item.appointmentId,
      userName: item.createBy, // 根据实际情况可能需要获取真实用户名
      time: `${parseTime(item.startTime)}`, // 组合时间（根据需求调整格式）
      type: item.type, // 类型转换
      method: item.type, // 咨询方式映射
      status: item.status // 状态转换
    }))
  })
}

onMounted(() => {
  getAppointmentList();
})
</script>

<style scoped>
.appointment-content {
  min-height: 200px;
  display: flex;
  flex-direction: column;
}

/* 调整空状态组件样式 */
:deep(.el-empty) {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 40px 0;
}

:deep(.el-empty__image) {
  width: 120px;
}

:deep(.el-empty__description) {
  margin-top: 12px;
  color: #909399;
  font-size: 14px;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
}

.label {
  color: #999;
}

.value {
  margin-right: 8px;
}

.consult-calendar {
  padding: 20px;
  background-color: #f5f6fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  font-size: 22px;
  color: #333;
}

.header p {
  font-size: 14px;
  color: #666;
}

.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.card {
  flex: 1;
  border-radius: 8px;
  padding: 15px;
  background-color: #fff;
  transition: all 0.3s ease;
}

.card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 8px;
}

.card-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.card-value.warning {
  color: #f5a623;
}

.card-value.success {
  color: #67c23a;
}

.calendar-card {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.cell-content {
  height: 100%;
  padding: 8px;
  position: relative;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.cell-content:hover {
  background-color: #f0f8ff;
}

.day {
  font-size: 16px;
  margin-bottom: 4px;
}

.appointment-mark {
  position: absolute;
  bottom: 2px;
  right: 2px;
}

/* 弹窗内容样式 */
:deep(.el-timeline-item__timestamp) {
  color: #666;
  font-size: 13px;
}

:deep(.el-card) {
  border-left: 4px solid #5b8ff9;
}
</style>
